<template>
  <div class="yearly">
    <!-- 查询表单 -->
    <filter-form
      planType="year"
      :showSearchKeyword="false"
      showYearPicker
      showDateTypeSelect
      showReportSelect
      :onSubmit="handleSearch"
      :onClear="handleClear"
      :onExport="showExportDialog"
    />
    <div class="statistics">
      <div class="item" @click="showStaticsDialog">
        <i class="el-icon-user-solid"></i>
        已填报人数：
        <span class="num">{{ importInfo.hasImport }}</span>
      </div>
      <div class="item" @click="showStaticsDialog">
        <i class="el-icon-user"></i>
        未填报人数：
        <span class="num">{{ importInfo.noImport }}</span>
      </div>
    </div>
    <!-- 月报列表 -->
    <week-month-report-list
      v-loading.fullscreen="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0)"
      planType="年"
      :loading="loading"
      :printing="printing"
      :weekRecords="weelyReportDatas"
      @onScrollLoad="handleScrollLoadData"
      @onReloadfetch="handleReLoadFetch"
    />
    <div v-if="noMore && weelyReportDatas.length" class="list-empty">
      没有更多了
    </div>
    <!-- 文件名输入对话框 -->
    <file-name-form-modal
      modalTitle="导出"
      :exportType="['toWord']"
      :exportName="exportName"
      :dialogVisible="dialogFileNameVisible"
      :onClose="
        () => {
          dialogFileNameVisible = false;
        }
      "
      :onSubmit="handleExportAction"
    />
    <!-- 周报填报情况 -->
    <weekly-report-statisc-modal
      :reportData="importInfo"
      :dialogVisible="dialogReportStaticsVisible"
      :onClose="
        () => {
          dialogReportStaticsVisible = false;
        }
      "
    />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import moment from "moment";
import { parseTime, filterObj, dataURLtoFile } from "@/utils/index.js";
import { getYearSchedule } from "@/api/plann.js";
import { getYearReportName } from "../utils/plan.js";

export default {
  computed: {
    ...mapGetters(["name", "id", "roles"]),
    device() {
      return this.$store.state.app.device;
    },
    username() {
      return this.name && this.name.split("(")[0];
    },
    isAdmin() {
      return this.roles.some((role) => ~role.indexOf("管理员"));
    },
    exportName() {
      return getYearReportName(this.queryParam)
    }
  },
  components: {
    FilterForm: () => import("../components/FilterForm.vue"),
    WeekMonthReportList: () => import("../components/WeekMonthReportList.vue"),
    FileNameFormModal: () => import("../components/FileNameFormModal"),
    WeeklyReportStatiscModal: () =>
      import("../components/WeeklyReportStatiscModal.vue"),
  },
  data() {
    return {
      weelyReportDatas: [],
      loading: false,
      printing: false,
      filterParam: null,
      queryParam: {},
      pdfName: "周报",
      pdfOption: "toPdf",
      dialogFileNameVisible: false,
      dialogReportStaticsVisible: false,
      page: 1, // 滚动加载页码
      pageSize: 5, // 每页加载数量
      noMore: false, // 是否还有更多
      importInfo: {},
    };
  },
  mounted() {
    this.fetchWeeklyPlanList();
  },
  methods: {
    parseTime,
    showStaticsDialog() {
      // 只有管理员可以打开查看具体信息
      // if (this.isAdmin) {
        this.dialogReportStaticsVisible = true;
      // }
    },
    showExportDialog() {
      if (!this.weelyReportDatas.length) {
        this.$message.warning("暂无数据可以导出");
        return;
      }
      this.dialogFileNameVisible = true;
    },
    // 滚动加载数据
    handleScrollLoadData() {
      if (!this.noMore && !this.loading) {
        this.fetchWeeklyPlanList(this.filterParam);
      }
    },
    // 更新表格数据 刷新请求
    handleReLoadFetch() {
      this.clearScrollParam();
      this.fetchWeeklyPlanList(this.filterParam);
    },
    // 处理导出菜单操作
    async handleExportAction(name, type) {
      // 如果选择导出到word
      if (type === "toWord") {
        this.handleFetchExport(name, type);
      }
    },
    // 请求后端 导出word文件
    async handleFetchExport(filename) {
      this.dialogFileNameVisible = false;
      const { protocol, host } = window.location;
      const params = filterObj({ ...this.queryParam, filename });
      const queryString = Object.keys(params)
        .map((key) => key + "=" + params[key])
        .join("&");
      window.open(
        `${protocol}//${host}/api/Work/year_workschedule/save_docx/?${queryString}`
      );
    },
    // 点击查询
    handleSearch(param) {
      const { user, year, dateType, userType, reportType, group } = param;
      const _param = {
        year: moment(year).year(),
        date_type: dateType,
        type: reportType,
      };
      // 当user为 u{id} 将u去除
      const _user = typeof user === "string" ? user.slice(1) : user;
      if (userType === "user") {
        _param.user = _user;
      } else {
        _param.department = _user;
      }
      if (group && group.length) {
        _param.group = group.join(",");
      }
      this.filterParam = _param;
      this.clearScrollParam();
      this.fetchWeeklyPlanList(_param);
    },
    // 清除滚动查询参数
    clearScrollParam() {
      this.page = 1;
      this.noMore = false;
      this.weelyReportDatas = [];
    },
    // 重置查询表单
    handleClear() {
      this.clearScrollParam();
      this.fetchWeeklyPlanList();
    },
    /**
     * 请求日历报告记录
     */
    async fetchWeeklyPlanList(filter = {}) {
      this.loading = true;
      this.queryParam = {
        year: moment().year(),
        date_type: "上半年",
        type: "person",
        ...filter,
      };

      try {
        const { data: result = {} } = await getYearSchedule({
          page: this.page,
          year: moment().year(),
          date_type: "上半年",
          type: "person",
          ...filter,
        });
        const {
          data,
          import: hasImport,
          noimport: noImport,
          import_list,
          no_import_user_list,
        } = result;
        if (this.page == 1) {
          this.importInfo = {
            hasImport,
            noImport,
            import_list,
            no_import_user_list,
          };
        }
        this.weelyReportDatas = [...this.weelyReportDatas, ...data];
        if (!data.length || data.length < this.pageSize) {
          this.noMore = true;
        }
        this.page++;
        this.loading = false;
      } catch (error) {
        this.loading = false;
      }
    },
  },
};
</script>
<style lang="scss" scope>
.yearly {
  .list-empty {
    text-align: center;
    margin-bottom: 10px;
    color: #999;
  }
  .statistics {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 45px;
    font-size: 14px;
    color: #666;
    padding: 10px 5px 10px 10px;
    cursor: pointer;
    margin: 0px auto -10px;
    width: 100%;
    max-width: 1200px;
    .item {
      margin-left: 20px;
      i {
        font-size: 18px;
      }
      .num {
        font-size: 16px;
        // font-weight: bold;
        color: #fb5b4a;
      }
    }
  }
}
</style>